<?php

namespace app\engine\controller;

use cmf\controller\HomeBaseController;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;

class LeaderController extends HomeBaseController
{
    /**
     * 加载首页
     * @return mixed|string
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function index()
    {
        $id = $this->request->param();
        $data = Db::name('leader')->where(['eid' => $id['id']])->select()->toArray();
        $this->assign('data', $data);
        $this->assign('id', $id['id']);
        return $this->fetch();
    }

    /**
     * 加载新增页
     * @return mixed|string
     */
    public function add()
    {
        $role = Db::name('role_user')->where(['user_id' => cmf_get_current_admin_id()])->value('role_id');
        if ($role == 2 || $role == 4 || $role == 5) {
            $this->error('无权限操作');
        }
        $data = $this->request->param();
        $group = Db::name('group')->field('name,type')->select();
        $this->assign('group', $group);
        $this->assign('id', $data['id']);
        return $this->fetch();
    }

    /**
     * 执行新增
     */
    public function doadd()
    {
        $data = $this->request->param();
        $files = request()->file('image');
        unset($data['image']);
        $kps = [];

        if (empty($data['name']) || empty($data['type']) || empty($data['insTime'])) {
            $this->error('请填写参数');
        }
        $check = Db::name('leader')->where(['name' => $data['name'], 'eid' => $data['eid']])->find();
        if ($check) {
            $this->error('姓名已存在');
        }
        $res = Db::name('leader')->insert($data);
        if (!$res) {
            $this->error('添加失败');
        }
        $this->success('添加成功');
    }

    /**
     * 单条记录查看
     * @return mixed|string
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function see()
    {
        $data = $this->request->param();
        $res = Db::name('leader')->where('id', $data['id'])->find();
        $res['insTime'] = date('Y-m-d', strtotime($res['insTime']));

        $group = Db::name('group')->field('name,type')->select();
        $this->assign('group', $group);
        $this->assign('res', $res);
        return $this->fetch();
    }

    /**
     * 执行编辑
     * @throws Exception
     * @throws PDOException
     */
    public function edit()
    {
        $role = Db::name('role_user')->where(['user_id' => cmf_get_current_admin_id()])->value('role_id');
        if ($role == 2 || $role == 4 || $role == 5) {
            $this->error('无权限操作');
        }
        $data = $this->request->param();
        $id = $data['id'];
        unset($data['id']);
        $files = request()->file('image');
        if ($files) {
            $check = Db::name('leader')->where('id', $id)->value('image');
            if ($check) {
                $cp = explode(',', $check);
                foreach ($cp as $v) {
                    $path = CMF_ROOT . 'public' . '/' . $v;
                    if (file_exists($path)) {
                        unlink($path);
                    }
                }
            }

            $kps = [];
            foreach ($files as $k => $file) {
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $file->move(CMF_ROOT . 'public' . '/' . 'uploads');
                if ($info) {
                    $kps[$k] = '/uploads/' . date('Ymd', time()) . '/' . $info->getFilename();
                } else {
                    $this->error($file->getError());
                }
            }
            $data['image'] = implode(',', $kps);
        } else {
            unset($data['image']);
        }

        if (empty($data['name']) || empty($data['type']) || empty($data['mobile']) || empty($data['card']) || empty($data['address']) || empty($data['insTime'])) {
            $this->error('请填写参数');
        }

        $res = Db::name('leader')->where('id', $id)->update($data);
        if (!$res) {
            $this->error('操作失败');
        }
        $this->success('操作成功');
    }

    /**
     * 删除分包组长
     * @throws Exception
     * @throws PDOException
     */
    public function del()
    {
        // $role = Db::name('role_user')->where(['user_id'=>cmf_get_current_admin_id()])->value('role_id');
        // if($role == 2 || $role == 4 || $role == 5){
        //     $this->error('无权限操作');
        // }
        $data = $this->request->param();

        Db::startTrans();
        try {
            Db::name('leader')->where('id', $data['id'])->delete();
            $worker = Db::name('worker')->where(['p_id' => $data['id']])->select();
            foreach ($worker as $k => $v) {
                if ($v['imgs']) {
                    $imgs = explode(',', $v['imgs']);
                    foreach ($imgs as $k => $v) {
                        $img = CMF_ROOT . $v;
                        if (file_exists($img)) {
                            unlink($img);
                        }
                    }
                }
            }
            Db::name('worker')->where(['p_id' => $data['id']])->delete();
        } catch (\Exception $e) {
            var_dump($e->getMessage());
            die;
            Db::rollback();
            $this->error('操作失败');
        }
        Db::commit();
        $this->success('操作成功');
    }

    /**
     * 项目分包组长下的员工
     */

    public function stafflist()
    {
        $id = $this->request->param();
        $data = Db::name('leader')->alias('a')->join('worker b', 'a.id = b.P_id')->where('P_id', $id['id'])->select()->toArray();
        $this->assign('data', $data);
        $this->assign('id', $id['id']);
        return $this->fetch();
    }

    /**
     * 加载新增员工页面
     */
    public function staffadd()
    {
        $role = Db::name('role_user')->where(['user_id' => cmf_get_current_admin_id()])->value('role_id');
        if ($role == 2 || $role == 4 || $role == 5) {
            $this->error('无权限操作');
        }
        $data = $this->request->param();
        $check = Db::name('worker')->where('id', $data['id'])->find();
        $this->assign('id', $data['id']);
        //        $this->assign('P_id', $check['P_id']);
        return $this->fetch();
    }

    /**
     * 添加员工
     */
    public function staff_add()
    {
        $data = $this->request->param();
        $arr = $data;
        if (empty($arr['name']) || empty($arr['mobile']) || empty($arr['incTime'])) {
            $this->error('请填写参数');
        }
        $files = request()->file('image');
        if ($files) {
            $kps = [];
            foreach ($files as $k => $file) {
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $file->move(CMF_ROOT . 'public' . '/' . 'uploads');
                if ($info) {
                    $kps[$k] = '/uploads/' . date('Ymd', time()) . '/' . $info->getFilename();
                } else {
                    $this->error($file->getError());
                }
            }
            $arr['imgs'] = implode(',', $kps);
        }
        unset($arr['image']);
        $res = Db::name('worker')->insert($arr);
        if (!$res) {
            $this->error('添加失败');
        }
        $this->success('添加成功');
    }

    /**
     * 员工编辑页
     * @return mixed|string
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function editstaff()
    {
        $data = $this->request->param();
        $res = Db::name('worker')->where('id', $data['id'])->find();

        $res['imgs'] = explode(',', $res['imgs']);
        foreach ($res['imgs'] as $k => &$v) {
            $v = 'http://' . $_SERVER['SERVER_NAME'] . $v;
        }
        $this->assign('res', $res);
        $this->assign('id', $res['id']);

        return $this->fetch();
    }

    /**
     * 执行员工编辑
     * @throws Exception
     * @throws PDOException
     */
    public function dostaff()
    {
        $data = $this->request->param();
        $files = request()->file('image');
        $id = $data['id'];
        unset($data['id']);
        $check = Db::name('worker')->where(['id' => $id])->find();

        // 处理要删除的图片
        $removeImg = isset($data['remove_image']) ? $data['remove_image'] : [];
        unset($data['remove_image']);

        // 处理保留的旧图片
        $oldImg = isset($data['old_image']) ? $data['old_image'] : [];
        unset($data['old_image']);

        // 处理身份证图片
        if (!is_null($files) || !empty($removeImg)) {
            $kps = [];
            // 如果有旧图片，先添加到数组中
            if (!empty($oldImg)) {
                // 处理旧图片，去除域名只保留路径
                foreach ($oldImg as $img) {
                    if (!empty($img)) {
                        // 如果图片路径包含域名，只保留路径部分
                        if (strpos($img, 'http://') === 0 || strpos($img, 'https://') === 0) {
                            $parsedUrl = parse_url($img);
                            $kps[] = $parsedUrl['path'];
                        } else {
                            $kps[] = $img;
                        }
                    }
                }
            } else if (!empty($check['imgs']) && empty($removeImg)) {
                // 如果没有指定旧图片但数据库中有图片且没有要删除的图片，则使用数据库中的图片
                $imgArray = explode(',', $check['imgs']);
                foreach ($imgArray as $img) {
                    if (!empty($img)) {
                        $kps[] = $img;
                    }
                }
            }

            // 处理新上传的图片
            if (!is_null($files)) {
                // 为每个文件创建唯一目录，而不是每批次
                foreach ($files as $file) {
                    // 为每个文件创建唯一目录
                    $uploadDir = 'uploads/' . date('YmdHis') . mt_rand(1000, 9999) . '_' . mt_rand(1000, 9999);
                    // 确保目录存在
                    if (!file_exists(CMF_ROOT . 'public/' . $uploadDir)) {
                        mkdir(CMF_ROOT . 'public/' . $uploadDir, 0777, true);
                    }

                    // 生成唯一文件名
                    $extension = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);
                    $newFilename = md5(uniqid(mt_rand(), true)) . '.' . $extension;

                    // 直接使用PHP的move_uploaded_file函数
                    $tmpName = $file->getInfo('tmp_name');
                    $destPath = CMF_ROOT . 'public/' . $uploadDir . '/' . $newFilename;

                    if (move_uploaded_file($tmpName, $destPath)) {
                        $kps[] = '/' . $uploadDir . '/' . $newFilename;
                    } else {
                        $this->error('文件上传失败');
                    }
                }
            }

            $data['imgs'] = implode(',', $kps);
        }

        if (empty($data['name']) || empty($data['mobile']) || empty($data['incTime'])) {
            $this->error('请填写参数');
        }
        unset($data['image']);
        $res = Db::name('worker')->where('id', $id)->update($data);
        if (!$res) {
            $this->error('操作失败');
        }
        $this->success('操作成功');
    }

    /**
     * 删除员工
     * @throws Exception
     * @throws PDOException
     */
    public function delstaff()
    {
        $role = Db::name('role_user')->where(['user_id' => cmf_get_current_admin_id()])->value('role_id');
        if ($role == 2 || $role == 4 || $role == 5) {
            $this->error('无权限操作');
        }
        $data = $this->request->param();
        $id = $data['id'];
        $check = Db::name('worker')->where(['id' => $id])->find();
        if ($check['imgs']) {
            $img = explode(',', $check['imgs']);
            foreach ($img as $k => $v) {
                $v = CMF_ROOT . $v;
                if (file_exists($v)) {
                    unlink($v);
                }
            }
        }
        $res = Db::name('worker')->where('id', $data['id'])->delete();
        if (!$res) {
            $this->error('操作失败');
        }
        $this->success('操作成功');
    }
}
